<?php
namespace app\mobile\controller;
use think\AjaxPage;
use think\Page;
use think\Db;
class Goods extends MobileBase {
	
	
    public function index(){
        $this->redirect(U('Index/index'));
    }

    /**
     * 分类页面显示
     */
    public function category(){
    	$limit = empty(I('limit'))?10:I('limit');
    	$start = empty(I('start'))?0:I('start');
    	$cid = empty(I('cid'))?1:I('cid');
    	$id = empty(I('type'))?1:I('type');//模型ID,不同分类对应模型不同
    	$prom_type = 0;
    	$category = M('goods_category')->where('id',$cid)->find();
    	if(empty($category)){
    		$this->error('该分类不存在或已删除',U('Index/index'));
    	}
    	//$where = 'prom_type = '.$prom_type.' and goods_type = '.$id.' and cat_id = '.$cid.' and is_on_sale=1';//只要普通商品
    	$where = array(
    	            'prom_type'=>$prom_type,
    	            'goods_type'=>$id,
    	            'cat_id'=>$cid,
    	            'is_on_sale'=>1 
    	        );
    	if(IS_POST){
    		$data = I('post.');

    	    if($data['attr']){
    		    $data['attr'] = array_filter($data['attr']); 	
    		}
    	    if(empty($data['attr'])){
    	    	$count = M('goods')->where($where)->count();
                $pagenum = ceil($count/$limit);
    	    	$goodsList = M('goods')->where($where)->limit($start,$limit)->order('shop_price')->select();
    	    	if(empty($goodsList)){
	    	        	$return_arr = array(
		                    'status' => -1,
		                    'msg' => '没有数据',
		                    'data' => null
		                );
		    		return $this->ajaxReturn($return_arr);
    	        }
    	        else{
    	        	$return_arr = array(
		                    'status' => 1,
		                    'msg' => '请求成功',
		                    'data' => array('goodsList'=>$goodsList,'pagenum'=>$pagenum)
		                );
		    		return $this->ajaxReturn($return_arr);
    	        }
    	    }else{
    	    	foreach($data['attr'] as $key=>$val){
	    	    	if(!empty($val[1])){
	    	    		$attr[$key]['attr_id'] = $val[0];
	    	    		$attr[$key]['attr_value'] = trim($val[1]);
	    	    	}
	    	    }
	    	    
	    	    $goods_exi_id = '';
	    	    $cache_attr = '';
	    	    $i=1;
	    	    foreach($attr as $key=>$val){
	    	    	$goods_id = M('goods_attr')->where(array('attr_id'=>$val['attr_id'],'attr_value'=>$val['attr_value']))->field('goods_id')->select();
	    	        if(empty($goods_id)){
	    	        	$return_arr = array(
			                    'status' => -1,
			                    'msg' => '没有数据',
			                    'data' => null
			                );
			    		return $this->ajaxReturn($return_arr);
	    	        }
	    	        else{
	    	        	if($i == 1){
	    	        	    foreach($goods_id as $k=>$v){
			    	        	$goods_exi_id[] = $v['goods_id'];
			    	        }
			    	        $i++;		
	    	        	}
	    	        	else{
	    	        		if(is_array($goods_exi_id)){
		    	        		foreach($goods_id as $k=>$v){
				    	        	if(in_array($v['goods_id'],$goods_exi_id)){
			    	        			$cache_attr[] = $v['goods_id'];
			    	        		}
				    	        }
			    	        }
			    	        $goods_exi_id = $cache_attr;	
	    	        	}
	    	        }
	    	    }
	    	    

	    	    $count = M('goods')->where(array('goods_id'=>array('in',$goods_exi_id)))->count();
	    	    $pagenum = ceil($count/$limit);

	    	    $where['goods_id']=array('in',$goods_exi_id);
	    	    $goodsList = M('goods')->where($where)->limit($start,$limit)->order('shop_price')->select();

	    	    foreach($goodsList as $key=>$val){
	    	    	$goodsList[$key]['thumbnail'] = goods_thum_images($val['goods_id'],200,200);
	    	    }
	    		$return_arr = array(
	                    'status' => 1,
	                    'msg' => '获取成功',
	                    'data' => array('goodsList'=>$goodsList,'pagenum'=>$pagenum)
	                );
	    		return $this->ajaxReturn($return_arr);
    	    }
    	    
    	}
    	
    	$goods_type = M('goods_type')->where('id',$id)->find(); 
        $attribute = M('goods_attribute')->where(array('type_id'=>$goods_type['id'],'attr_input_type'=>1,'attr_index'=>1))->limit($start,$limit)->select();
        if(!empty($attribute)){
        	foreach($attribute as $key=>$val){
        		$attribute[$key]['attr_values'] = explode(PHP_EOL,$val['attr_values']);
        	}
        }
        $count = M('goods')->where($where)->count();
        $pagenum = ceil($count/$limit);
        $goodsList = M('goods')->where($where)->limit($start,$limit)->order('shop_price')->select();
        $this->assign('attribute',$attribute);
        $this->assign('goodsList',$goodsList);
        $this->assign('type',$id);
        $this->assign('cid',$cid);
        $this->assign('limit',$limit);
        $this->assign('pagenum',$pagenum);
        $this->assign('category',$category);

        return $this->fetch();
    }

    
    
    /**
     * 分类列表
     */
    public function categoryList(){
    	$limit = empty(I('limit'))?10:I('limit');
    	$start = empty(I('start'))?0:I('start');
    	$id = empty(I('type'))?1:I('type');//模型ID,不同分类对应模型不同
    	$prom_type = 0;
    	$where = 'prom_type = '.$prom_type.' and goods_type = '.$id.' and is_on_sale=1';//只要普通商品
    	$where = array(
    	            'prom_type'=>$prom_type,
    	            'goods_type'=>$id,
    	            'is_on_sale'=>1 
    	        );
    	if(IS_POST){
    		$data = I('post.');
    		if($data['attr']){
    		    $data['attr'] = array_filter($data['attr']); 	
    		}
    	    if(empty($data['attr'])){
    	    	$count = M('goods')->where($where)->count();
                $pagenum = ceil($count/$limit);
    	    	$goodsList = M('goods')->where($where)->limit($start,$limit)->order('shop_price')->select();
    	    	if(empty($goodsList)){
	    	        	$return_arr = array(
		                    'status' => -1,
		                    'msg' => '没有数据',
		                    'data' => null
		                );
		    		return $this->ajaxReturn($return_arr);
    	        }
    	        else{
    	        	$return_arr = array(
		                    'status' => 1,
		                    'msg' => '请求成功',
		                    'data' => array('goodsList'=>$goodsList,'pagenum'=>$pagenum)
		                );
		    		return $this->ajaxReturn($return_arr);
    	        }
    	    }else{
    	    	foreach($data['attr'] as $key=>$val){
	    	    	if(!empty($val[1])){
	    	    		$attr[$key]['attr_id'] = $val[0];
	    	    		$attr[$key]['attr_value'] = trim($val[1]);
	    	    	}
	    	    }
	    	    $goods_exi_id = '';
	    	    $cache_attr = '';
	    	    $i=1;
	    	    foreach($attr as $key=>$val){
	    	    	$goods_id = M('goods_attr')->where(array('attr_id'=>$val['attr_id'],'attr_value'=>$val['attr_value']))->field('goods_id')->select();
	    	        if(empty($goods_id)){
	    	        	$return_arr = array(
			                    'status' => -1,
			                    'msg' => '没有数据',
			                    'data' => null
			                );
			    		return $this->ajaxReturn($return_arr);
	    	        }
	    	        else{
	    	        	if($i == 1){
	    	        	    foreach($goods_id as $k=>$v){
			    	        	$goods_exi_id[] = $v['goods_id'];
			    	        }
			    	        $i++;	
	    	        	}
	    	        	else{
	    	        		if(is_array($goods_exi_id)){
		    	        		foreach($goods_id as $k=>$v){
				    	        	if(in_array($v['goods_id'],$goods_exi_id)){
			    	        			$cache_attr[] = $v['goods_id'];
			    	        		}
				    	        }
			    	        }
			    	        $goods_exi_id = $cache_attr;	
	    	        	}
	    	        }
	    	    }

	    	    $count = M('goods')->where(array('goods_id'=>array('in',$goods_exi_id),'prom_type'=>$prom_type))->count();
	    	    $pagenum = ceil($count/$limit);
	    	    $where['goods_id'] = array('in',$goods_exi_id);
	    	    $goodsList = M('goods')->where($where)->limit($start,$limit)->order('shop_price')->select();
	    	    foreach($goodsList as $key=>$val){
	    	    	$goodsList[$key]['thumbnail'] = goods_thum_images($val['goods_id'],200,200);
	    	    }
	    		$return_arr = array(
	                    'status' => 1,
	                    'msg' => '获取成功',
	                    'data' => array('goodsList'=>$goodsList,'pagenum'=>$pagenum)
	                );
	    		return $this->ajaxReturn($return_arr);
    	    }
    	    
    	}
    	
    	$goods_type = M('goods_type')->where('id',$id)->find(); 
        $attribute = M('goods_attribute')->where(array('type_id'=>$goods_type['id'],'attr_input_type'=>1,'attr_index'=>1))->limit($start,$limit)->select();
        if(!empty($attribute)){
        	foreach($attribute as $key=>$val){
        		$attribute[$key]['attr_values'] = explode(PHP_EOL,$val['attr_values']);
        	}
        }
        $count = M('goods')->where($where)->count();
        $pagenum = ceil($count/$limit);
        $goodsList = M('goods')->where($where)->limit($start,$limit)->order('shop_price')->select();
        $this->assign('attribute',$attribute);
        $this->assign('goodsList',$goodsList);
        $this->assign('type',$id);
        $this->assign('limit',$limit);
        $this->assign('pagenum',$pagenum);

        
        return $this->fetch();
    }

    /**
     * 商品列表页 ajax 翻页请求 搜索
     */
    public function ajaxGoodsList() {
        $where ='';

        $cat_id  = I("id",0); // 所选择的商品分类id
        if($cat_id > 0)
        {
            $grandson_ids = getCatGrandson($cat_id);
            $where .= " WHERE cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
        }

        $result = DB::query("select count(1) as count from __PREFIX__goods $where ");
        $count = $result[0]['count'];
        $page = new AjaxPage($count,10);

        $order = " order by goods_id desc"; // 排序
        $limit = " limit ".$page->firstRow.','.$page->listRows;
        $list = DB::query("select *  from __PREFIX__goods $where $order $limit");

        $this->assign('lists',$list);
        $html = $this->fetch('ajaxGoodsList'); //return $this->fetch('ajax_goods_list');
       exit($html);
       
       
       
    }

    /**
     * 商品详情页
     */
    public function goodsInfo(){
        C('TOKEN_ON',true);        
        $goodsLogic = new \app\home\logic\GoodsLogic();
        $goods_id = I("get.id");
        $goods = M('Goods')->where("goods_id", $goods_id)->find();
        if(empty($goods)){
        	$this->error('该商品已经下架',U('Index/index'));
        }
        if($goods['brand_id']){
            $brnad = M('brand')->where("id", $goods['brand_id'])->find();
            $goods['brand_name'] = $brnad['name'];
        }
        $goods_images_list = M('GoodsImages')->where("goods_id", $goods_id)->select(); // 商品 图册
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->join("f_goods_attribute","f_goods_attribute.attr_id = f_goods_attr.attr_id")->where(array("f_goods_attr.goods_id"=>$goods_id,"f_goods_attribute.attr_index"=>1))->select(); // 查询商品属性表
		$filter_spec = $goodsLogic->get_spec($goods_id);  
         
        $spec_goods_price  = M('spec_goods_price')->where("goods_id", $goods_id)->getField("key,price,store_count"); // 规格 对应 价格 库存表
        //M('Goods')->where("goods_id=$goods_id")->save(array('click_count'=>$goods['click_count']+1 )); //统计点击数
        $commentStatistics = $goodsLogic->commentStatistics($goods_id);// 获取某个商品的评论统计     
        $this->assign('spec_goods_price', json_encode($spec_goods_price,true)); // 规格 对应 价格 库存表
      	$goods['sale_num'] = M('order_goods')->where(['goods_id'=>$goods_id,'is_send'=>1])->count();

      	//取10条评论消息
        $comment_list = M("comment")
                        ->alias("c")
                        ->join("f_users u","c.user_id = u.user_id","left")
                        ->where(array("c.goods_id" =>$goods_id,"c.is_show"=>1))
                        ->order("c.add_time desc")
                        ->field("c.*,u.head_pic")
                        ->limit(10)
                        ->select();
        foreach ($comment_list as $key => $value){
            $comment_list[$key]['img'] = unserialize($value['img']);
        }
        
        $activity_info = ''; 
        //限时抢购
        if($goods['prom_type'] == 1)
        {
        	$activity_info = M('flash_sale')->where(['goods_id'=>$goods_id,'start_time'=>['<=',time()],'end_time'=>['>=',time()]])->find(); 
        }
        //团购
        if($goods['prom_type'] == 2){
        	$activity_info = M('GroupBuy')->where(['goods_id'=>$goods_id,'start_time'=>['<=',time()],'end_time'=>['>=',time()]])->find(); 
        }
        //促销优惠
        if($goods['prom_type'] == 3){
        	$activity_info = M('prom_goods')->where(['id'=>$goods['prom_id'],'start_time'=>['<=',time()],'end_time'=>['>=',time()]])->find(); 
        }
        
        //当前用户收藏
        $user_id = cookie('user_id');
        $this->assign('goods_attribute',$goods_attribute);//属性值     
        $this->assign('goods_attr_list',$goods_attr_list);//属性列表
        $this->assign('filter_spec',$filter_spec);//规格参数
        $this->assign('goods_images_list',$goods_images_list);//商品缩略图
        $this->assign('goods',$goods);
        $this->assign('activity_info',$activity_info);
        $this->assign('comment_list',$comment_list);
        return $this->fetch();
    }

    /**
     * 商品详情页
     */
    public function detail(){
        //  form表单提交
        C('TOKEN_ON',true);
        $goods_id = I("get.id/d");
        $goods = M('Goods')->where("goods_id", $goods_id)->find();
        $this->assign('goods',$goods);
        return $this->fetch();
    }

    /*
     * 商品评论
     */
    public function comment(){
        $goods_id = I("goods_id/d",0);
        $this->assign('goods_id',$goods_id);
        return $this->fetch();
    }

    /*
     * ajax获取商品评论
     */
    public function ajaxComment(){        
        $goods_id = I("goods_id/d",0);
        $commentType = I('commentType','1'); // 1 全部 2好评 3 中评 4差评
        if($commentType==5){
        	$where = "goods_id = :goods_id and parent_id = 0 and img !='' ";
        }else{
        	$typeArr = array('1'=>'0,1,2,3,4,5','2'=>'4,5','3'=>'3','4'=>'0,1,2');
        	$where = "goods_id = :goods_id and parent_id = 0 and ceil((deliver_rank + goods_rank + service_rank) / 3) in($typeArr[$commentType])";
        }
        $count = M('Comment')->where($where)->bind(['goods_id'=>$goods_id])->count();
		$page_count = 5;
        $page = new AjaxPage($count,$page_count);
        $list = M('Comment')
				->alias('c')
				->join('__USERS__ u','u.user_id = c.user_id','LEFT')
				->where($where)
				->bind(['goods_id'=>$goods_id])
				->order("add_time desc")
				->limit($page->firstRow.','.$page->listRows)
				->select();
		$replyList = M('Comment')->where(['goods_id'=>$goods_id,'parent_id'=>['>',0]])->order("add_time desc")->select();
        foreach($list as $k => $v){
            $list[$k]['img'] = unserialize($v['img']); // 晒单图片            
        }
		$this->assign('goods_id',$goods_id);//商品id
        $this->assign('commentlist',$list);// 商品评论
		$this->assign('commentType',$commentType);// 1 全部 2好评 3 中评 4差评 5晒图
        $this->assign('replyList',$replyList); // 管理员回复
		$this->assign('count', $count);//总条数
		$this->assign('page_count', $page_count);//页数
		$this->assign('current_count', $page_count*I('p'));//当前条
		$this->assign('p', I('p'));//页数
        return $this->fetch();
    }
    
    /*
     * 获取商品规格
     */
    public function goodsAttr(){
        $goods_id = I("get.goods_id/d",0);
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表
        $this->assign('goods_attr_list',$goods_attr_list);
        $this->assign('goods_attribute',$goods_attribute);
        return $this->fetch();
    }

    /**
     * 积分商城
     */
    public function integralMall()
    {
        $rank= I('get.rank');
        //以兑换量（购买量）排序
        if($rank == 'num'){
            $ranktype = 'sales_sum';
            $order = 'desc';
        }
        //以需要积分排序
        if($rank == 'integral'){
            $ranktype = 'exchange_integral';
            $order = 'desc';
        }
        $point_rate = tpCache('shopping.point_rate');
        $goods_where = array(
            'is_on_sale' => 1,  //是否上架
        );
        //积分兑换筛选
        $exchange_integral_where_array = array(array('gt',0));

        // 分类id
        if (!empty($cat_id)) {
            $goods_where['cat_id'] = array('in', getCatGrandson($cat_id));
        }
        //我能兑换
        $user_id = cookie('user_id');
        if (!empty($user_id)) {
            //获取用户积分
            $user_pay_points = intval(M('users')->where(array('user_id' => $user_id))->getField('pay_points'));
            if ($user_pay_points !== false) {
                array_push($exchange_integral_where_array, array('lt', $user_pay_points));
            }
        }
        $goods_where['exchange_integral'] =  $exchange_integral_where_array;  //拼装条件
        $goods_list_count = M('goods')->where($goods_where)->count();   //总页数
        $page = new Page($goods_list_count, 15);
        $goods_list = M('goods')->where($goods_where)->order($ranktype ,$order)->limit($page->firstRow . ',' . $page->listRows)->select();
        $goods_category = M('goods_category')->where(array('level' => 1))->select();

        $this->assign('goods_list', $goods_list);
        $this->assign('page', $page->show());
        $this->assign('goods_list_count',$goods_list_count);
        $this->assign('goods_category', $goods_category);//商品1级分类
        $this->assign('point_rate', $point_rate);//兑换率
        $this->assign('totalPages',$page->totalPages);//总页数
        if(IS_AJAX){
            return $this->fetch('ajaxIntegralMall'); //获取更多
        }
        return $this->fetch();
    }

     /**
     * 商品搜索列表页
     */
    public function search(){
    	$filter_param = array(); // 帅选数组
    	$id = I('get.id/d',0); // 当前分类id
    	$brand_id = I('brand_id',0);    	    	
    	$sort = I('sort','goods_id'); // 排序
    	$sort_asc = I('sort_asc','asc'); // 排序
    	$price = I('price',''); // 价钱
    	$start_price = trim(I('start_price','0')); // 输入框价钱
    	$end_price = trim(I('end_price','0')); // 输入框价钱
    	if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱   	 
    	$filter_param['id'] = $id; //加入帅选条件中
    	$brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中    	    	
    	$price  && ($filter_param['price'] = $price); //加入帅选条件中
        $q = urldecode(trim(I('q',''))); // 关键字搜索
        $q  && ($_GET['q'] = $filter_param['q'] = $q); //加入帅选条件中
        $qtype = I('qtype','');
        $where  = array('is_on_sale' => 1);
        if($qtype){
        	$filter_param['qtype'] = $qtype;
        	$where[$qtype] = 1;
        }
        if($q) $where['goods_name'] = array('like','%'.$q.'%');
        
    	$goodsLogic = new \app\home\logic\GoodsLogic(); // 前台商品操作逻辑类
    	$filter_goods_id = M('goods')->where($where)->cache(true)->getField("goods_id",true);

    	// 过滤帅选的结果集里面找商品
    	if($brand_id || $price)// 品牌或者价格
    	{
    		$goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
    	}

        //筛选网站自营,入驻商家,货到付款,仅看有货,促销商品
        $sel = I('sel');
        if($sel)
        {
            $goods_id_4 = $goodsLogic->get_filter_selected($sel);
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_4);
        }

    	$filter_menu  = $goodsLogic->get_filter_menu($filter_param,'search'); // 获取显示的帅选菜单
    	$filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'search'); // 帅选的价格期间
    	$filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'search',1); // 获取指定分类下的帅选品牌    	 
    	
    	$count = count($filter_goods_id);
    	$page = new Page($count,12);
    	if($count > 0)
    	{
    		$goods_list = M('goods')->where("goods_id", "in", implode(',', $filter_goods_id))->order("$sort $sort_asc")->limit($page->firstRow.','.$page->listRows)->select();
    		$filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
    		if($filter_goods_id2)
    			$goods_images = M('goods_images')->where("goods_id", "in", implode(',', $filter_goods_id2))->cache(true)->select();
    	}
    	$goods_category = M('goods_category')->where('is_show=1')->cache(true)->getField('id,name,parent_id,level'); // 键值分类数组
    	$this->assign('goods_list',$goods_list);
    	$this->assign('goods_category',$goods_category);
    	$this->assign('goods_images',$goods_images);  // 相册图片
    	$this->assign('filter_menu',$filter_menu);  // 帅选菜单     
    	$this->assign('filter_brand',$filter_brand);// 列表页帅选属性 - 商品品牌
    	$this->assign('filter_price',$filter_price);// 帅选的价格期间    	
    	$this->assign('filter_param',$filter_param); // 帅选条件    	
    	$this->assign('page',$page);// 赋值分页输出
    	$this->assign('sort_asc', $sort_asc == 'asc' ? 'desc' : 'asc');
    	C('TOKEN_ON',false);
        if(input('is_ajax'))
            return $this->fetch('ajaxGoodsList');
        else
            return $this->fetch();
    }

    /**
     * 商品搜索列表页
     */
    public function ajaxSearch()
    {
        return $this->fetch();
    }

    /**
     * 品牌街
     */
    public function brandstreet()
    {
        $getnum = 9;   //取出数量
        $goods=M('goods')->where(array('is_recommend'=>1,'is_on_sale'=>1))->page(1,$getnum)->cache(true,FT_CACHE_TIME)->select(); //推荐商品
        for($i=0;$i<($getnum/3);$i++){
            //3条记录为一组
            $recommend_goods[] = array_slice($goods,$i*3,3);
        }
        $where = array(
            'is_hot' => 0,  //1为推荐品牌
        );
        $count = M('brand')->where($where)->count(); // 查询满足要求的总记录数
        $Page = new Page($count,20);
        $show = $Page->show();// 分页显示输出
        $brand_list = M('brand')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('sort desc')->select();
        $this->assign('Page',$show);  //赋值分页输出
        $this->assign('recommend_goods',$recommend_goods);  //品牌列表
        $this->assign('brand_list',$brand_list);            //推荐商品
        if(I('is_ajax')){
            return $this->fetch('ajaxBrandstreet');
        }
        return $this->fetch();
    }

    /**
     * 看相似
     */
    public function similar(){
        $good_id = I('id','');
        $now_good = M('goods')->where("goods_id=$good_id")->find();   //当前商品
        $where_id_list = M('goods')->field('cat_id,spec_type')->where("goods_id=$good_id")->find(); //相似条件，分类id,类型id
        $count = M('goods')->where($where_id_list) ->count();    //符合条件的总数
        $pagesize = C('PAGESIZE');  //每页显示数
        $Page = new Page($count,$pagesize);
        $goods_list = M('goods')->where($where_id_list) ->limit($Page->firstRow.','.$Page->listRows)->select();  //获取相似商品
        $this->assign('goods_list',$goods_list);
        $this->assign('now_good',$now_good);
        if(I('is_ajax')){
            return $this->fetch('ajax_similar');
        }
        return $this->fetch();
    }
    
    
    
    /**
    * 一元夺宝详情页
    */ 
    public function indianaList(){
       
        $now = time();
        $lists = M('indiana_sale')->where("is_end=0 and start_time<$now")->select();
        $lists_end = M('user_indiana')->alias('a')->join('indiana_sale b','b.id = a.indiana_id')
                     ->join('users c','a.uid = c.user_id')
                     ->where(array('b.is_end'=>1,'is_praise'=>1))
                     ->field('a.*,b.goods_id,b.title,c.nickname')->select();
        $this->assign('lists',$lists);
        $this->assign('lists_end',$lists_end);
        return $this->fetch();        
    }
    
    
    /**
    * 一元夺宝详开奖
    */ 
    public function indianaBingo(){
        
        $lists = M('indiana_sale')->where(array('is_end'=>0))->order('id desc')->select();
        foreach($lists as $key=>$val){
        	if($val['stock_num'] ==0){//售空即可开奖
        		$numbers = json_decode($val['indiana_number'],true);
                
                //排除掉指定人员
                $user_nbry = array(4,68,39,597,305,260,139);
				$n_list = M('user_indiana')->where(array('indiana_id'=>$val['id'],'pay_status'=>1))->where(array('uid'=>array('in',$user_nbry)))->field('indiana_number')->select();
		        $nb_num = array();
		        if($n_list){
			        foreach($n_list as $nk=>$nvl){
			        	$arr = json_decode($nvl['indiana_number'],true);
			        	$nb_num = array_merge($nb_num,$arr);//合并中奖码
			        }
			        $numbers = array_diff($numbers,$nb_num);
			        foreach($numbers as $k3 => $v3){
			        	$new_arr[] = $v3;
			        }
			        $numbers = $new_arr;
		        }
        		$max = count($numbers)-1;
        		$win_key = rand(0,$max);
        		$win_number = $numbers[$win_key];//获取开奖号码
        		
        		//查找获奖人员
        		$res = M('user_indiana')->where(array('indiana_id'=>$val['id'],'pay_status'=>1))->select();
        		if($res){
        		    foreach($res as $k=>$v){
	        			$my_numbers = json_decode($v['indiana_number'],true);
	        			if(in_array($win_number,$my_numbers)){
	        				M('user_indiana')->where('id',$v['id'])->save(array('is_praise'=>1));
	        				$msg = "尊敬的用户，在第".$val['id']."期夺宝活动中，您夺宝成功，感谢您的参与！";
	        			    SendMessage(0,1,$msg,array($v['uid']),'一元夺宝开奖结果通知');//发送站内消息
	        			    $winner_id = $v['uid'];//获取中奖者ID记录日志
	        			}
	        			else{
	        				$msg = "尊敬的用户，在第".$val['id']."期夺宝活动中，您夺宝失败，感谢您的参与！";
	        			    SendMessage(0,1,$msg,array($v['uid']),'一元夺宝开奖结果通知');//发送站内消息
	        			}
	        		}
	        	    $r = M('indiana_sale')->where(array('id'=>$val['id']))->save(array('is_end'=>1,'win_time'=>time(),'win_number'=>$win_number));
	        	    //写入开奖日志
	        	    $msg = "第".$val['id']."期开奖成功！获奖用户ID：".$winner_id."，开奖编码：".$win_number."\r\n";
	        	    log_indiana($msg);	
        		}
        		else{
        			$r = M('indiana_sale')->where(array('id'=>$val['id']))->save(array('is_end'=>1,'win_time'=>time(),'win_number'=>$win_number));
        			$msg = "第".$val['id']."期开奖失败，购买用户为空，开奖编码：".$win_number."\r\n";
	        	    log_indiana($msg);
        		}
        	}
        	
        	if($val['stock_num']!=0 && $val['end_time']<time()){//已过期但还未售空的活动进行退款处理
        		$res2 = M('user_indiana')->where(array('indiana_id'=>$val['id'],'pay_status'=>1))->select();
        		if($res2){//向购买用户退款
        		    foreach($res2 as $k2=>$v2){
        		    	//退款至余额
//      		    	$user_money = M('users')->where('user_id',$v2['uid'])->getField('user_money');
//      		    	$user_money += $v2['order_amount'];
//	        			M('users')->where('user_id',$v2['uid'])->save(array('user_money'=>$user_money));
//	        			income_action(2,8,'一元夺宝退款',$v2['order_amount'],$v2['uid']);//记录退款流水
	        			
	        			//退款至付款账户，从付款记录中找出一些信息，生成退款记录
	        			$pay_log = M('pay_log')->where(array('order_sn'=>$v2['order_sn']))->find();
	        			if($pay_log){
	        				$r_data = array('pay_id'=>$pay_log['id'],
	        				         'out_trade_no' => $pay_log['out_trade_no'],
	        				         'user_id' => $pay_log['user_id'],
	        				         'refund_fee' => $pay_log['total_fee'],
	        				         'addtime' => time(),
	        				         'return_type' => 1
	        				         );
	        				$refund_id = M('refund_log')->insert($r_data);
	        				$ref_res = order_WX_refund($refund_id);
	        				if($ref_res){
	        				    $msg = "尊敬的用户，由于第".$val['id']."期夺宝活动逾期， 夺宝失败，已于".date("Y-m-d H:i:s")."退款￥".$v2['order_amount'].",请查收，感谢您的参与！";
	        			        SendMessage(0,1,$msg,array($v2['uid']),'一元夺宝退款通知');//发送站内消息
	        			    }
	        			    else{
	        			    	//记录错误日志
	        			    	$msg = "第".$val['id']."期一元夺宝活动中，ID为".$v2['uid']."的用户退款失败，退款商户订单号为：".$pay_log['out_trade_no']."\r\n";
	        	                log_indiana($msg);
	        			    }
	        			}
	        		}
	        	    $r = M('indiana_sale')->where(array('id'=>$val['id']))->save(array('is_end'=>1));
	        	    //写入开奖日志
	        	    $msg = "第".$val['id']."期活动过期，已完成退款！\r\n";
	        	    log_indiana($msg);	
        		}
        		else{
        			$r = M('indiana_sale')->where(array('id'=>$val['id']))->save(array('is_end'=>1));
        			$msg = "第".$val['id']."期活动过期，购买用户为空，无需退款\r\n";
	        	    log_indiana($msg);
        		}
        	}
        }     
    }
    
    
    /**
    * 一元夺宝往期
    */ 
    public function indianaBefore(){
        
        $lists = M('indiana_sale')->where(array('is_end'=>1))->select();
        $this->assign('lists',$lists);
        return $this->fetch();        
    }
    
    
    
    /**
    * 一元夺宝详预告
    */ 
    public function indianaAfter(){
        

        $lists = M('indiana_sale')->alias('a')->join('goods b','b.goods_id = a.goods_id')
                 ->where('is_end = 0 and start_time > '.time())
                 ->field('a.*,b.shop_price')->select();
        $this->assign('lists',$lists);
        return $this->fetch();               
    }
    
    /**
     * AjaxindianaInfo
     * 获取夺宝详情
     */
    public function ajaxIndianaInfo(){
    	$id = I('id/d');
    	//获取中奖码
    	$win_number = M('indiana_sale')->where('id',$id)->getField('win_number');
    	
    	$res = M('user_indiana')->alias('a')->join('indiana_sale b','b.id = a.indiana_id')
    	           ->join('goods c','c.goods_id = b.goods_id')
    	           ->join('users d','d.user_id = a.uid')
                   ->where(array('b.id'=>$id))
                   ->where('a.indiana_number like "%'.$win_number.'%"')
                   ->field('a.*,b.goods_id,b.title,b.price,c.goods_name,c.shop_price,d.nickname,c.original_img,a.indiana_number,b.win_time')->find();  
        if($res){
        	$indiana_number = json_decode($res['indiana_number'],ture);
        	$res['indiana_number'] = $indiana_number[0];
        	$res['win_time'] = date('Y-m-d',$res['win_time']);
        	$return_arr = array(
	            'status' => 1,
	            'msg' => '获取数据成功',
	            'data' => $res,
	        );
	    	return  $this->ajaxReturn($return_arr);     
        }else{
        	$return_arr = array(
	            'status' => -1,
	            'msg' => '获取数据失败',
	            'data' => '',
	        );
    	    return  $this->ajaxReturn($return_arr);     
        }       
    }
    
    
    /**
     * 
     * 往期夺宝参与实况
     */
    public function ajaxIndianaUser(){
    	$id = I('id/d');
    	//获取中奖码
    	//查询已参与夺宝的用户
        $indiana_order = M('user_indiana')->where(array('indiana_id'=>$id,'pay_status'=>1))->select();
        if(!empty($indiana_order)){
        	foreach($indiana_order as $key=>$val){
        		$user = M('users')->where('user_id',$val['uid'])->field('nickname,mobile,head_pic')->find();
        		$user_list[] = $user;
        		$user_list[$key]['add_time'] = date("Y-m-d H:i:s",$val['addtime']);
        		$user_list[$key]['num'] = $val['num'];
        	}
        	$return_arr = array(
	            'status' => 1,
	            'msg' => '获取数据成功',
	            'data' => $user_list,
	        );
	    	return  $this->ajaxReturn($return_arr);   
        }
        else{
        	$return_arr = array(
	            'status' => -1,
	            'msg' => '获取数据失败',
	            'data' => '',
	        );
    	    return  $this->ajaxReturn($return_arr);     
        }  
    }
    
    
    
    
    /**
    * 一元夺宝详情页
    */ 
    public function indianaInfo(){
    	
        $id = I("get.id/d");
        $goodsLogic = new \app\home\logic\GoodsLogic();
        
        $indiana = M('indiana_sale')->where("id",$id)->find();
        $goods_id = $indiana['goods_id'];
        $goods = M('Goods')->where("goods_id",$goods_id)->find();

        if(empty($goods)){
        	$this->error('该商品已经下架',U('Index/index'));
        }
     
        $goods_images_list = M('GoodsImages')->where("goods_id", $goods_id)->select(); // 商品 图册
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表
	    $filter_spec = $goodsLogic->get_spec($goods_id);
               
 
        M('Goods')->where("goods_id", $goods_id)->save(array('click_count'=>$goods['click_count']+1 )); //统计点击数
        $point_rate = tpCache('shopping.point_rate');
        
        //查询已参与夺宝的用户
        $indiana_order = M('user_indiana')->where(array('indiana_id'=>$id,'pay_status'=>1))->select();
        if(!empty($indiana_order)){
        	foreach($indiana_order as $key=>$val){
        		$exi_user = M('users')->where('user_id',$val['uid'])->field('nickname,mobile,head_pic')->find();
        		$indiana_order[$key]['user'] = $exi_user;
        	}
        }
        
        $user_id = $_COOKIE['user_id'];
        if($user_id){
            $user = M('users')->where('user_id',$user_id)->find();
        }
        else{
        	//未登录，跳转登录
        }
        
        $this->assign('is_val',$user['mobile_validated']);//用户是否验证手机
        $this->assign('goods_images_list',$goods_images_list);//商品缩略图
        $this->assign('goods',$goods);
        $this->assign('indiana',$indiana);
        $this->assign('indiana_order',$indiana_order);
        $this->assign('point_rate',$point_rate);    
        $this->assign('goods_attribute',$goods_attribute);
        $this->assign('goods_attr_list',$goods_attr_list);//属性列表

        return $this->fetch();        
    }
    
    
    public function indianaOrder(){
    	
    	$id = empty(I("id/d"))?I("indiana_id/d"):I("id/d");
    	$goodsLogic = new \app\home\logic\GoodsLogic();
        $indiana = M('indiana_sale')->where("id",$id)->find();
        $goods_id = $indiana['goods_id'];
        $goods = M('Goods')->where("goods_id",$goods_id)->find();
        $user_id = cookie('user_id');
        $user = M('users')->where('user_id',$user_id)->find();
		if(!$user){
			$this->error('亲，请先登录');
		}
    	if(IS_POST){
    		$data = I("post.");
    		$data['addtime'] = time();
    		$data['order_sn'] = "YDB".$user_id.time();
    		$data['order_status'] = 0;
    		$data['pay_status'] = 0;
    		$data['uid'] = $user_id;
			if($data['num']<=0){
				$return_arr = array(
	                'status' => -1,
	                'msg' => '请不要非法操作',
	                'data' => '购买数量必须为正数！',
	            );
		    	return  $this->ajaxReturn($return_arr);
			}
    		$data['shopping_info'] = array('shopping_id'=>'','invoice_no'=>'');
    		if($indiana['stock_num']<$data['num']){
		   	    $return_arr = array(
	                'status' => -1,
	                'msg' => '兑奖编码库存不足',
	                'data' => '请勿进行非法操作！',
	            );
		    	return  $this->ajaxReturn($return_arr);
    		   	  
    		}
    	
    		$r = M("user_indiana")->add($data);
    		if($r){
    			indiana_order_action('insert',$r,'下单');//记录日志
    			$return_arr = array(
	                'status' => 1,
	                'msg' => '下单成功',
	                'data' => array('url' => U('Mobile/Cart/indiana_pay',array('id'=>$r))),
	            );
		    	return  $this->ajaxReturn($return_arr);
    		}
    		
    	}else{
	        $this->assign('goods',$goods);
	        $this->assign('user',$user);
	        $this->assign('indiana',$indiana);
	    	return $this->fetch(); 	
    	}
    }
    
    
    /*
     * 热销商品
     */
    public function hotGoodsList() {
        $goods_list = M("goods")->where(array("prom_type"=>0,"type"=>0))->order("sales_sum desc")->limit(40)->select();
        $this->assign("goods_list",$goods_list);
        return $this->fetch();
    }
    
    /*
     * 超级单品
     */
    public function goodSupper() {
    	$cat_id = empty(I('cid'))?4:I('cid');
    	if(!$cat_id){
    		$this->error('缺少参数，请勿非法操作！');
    	}
        $time = time();
        //取4件限量商品
        $time_goods_list = M("goods")
                        ->alias("g")
                        ->join("f_flash_sale fs","fs.goods_id = g.goods_id")
                        ->where("g.cat_id=$cat_id and g.prom_type=1 and fs.start_time<$time  and fs.end_time>$time and fs.is_end=0")
                        ->order('fs.id desc')
                        ->limit(4)
                        ->select();
        //取两件返现商品
        $score_goods_list = M("goods")->where("cat_id=$cat_id and give_integral >0 and type=0")->order("last_update desc")->limit(2)->select();
        $this->assign("time_goods_list",$time_goods_list);
        $this->assign("score_goods_list",$score_goods_list);
        return $this->fetch();
    }
    
    
    /*
     * 商品评论页面
     */
    public function goods_comment() {
        $limit = 1;//每页显示的记录数
        $page = I("post.page",0);//当前页数
        $goods_id = I("id");
         //取10条评论消息
        $comment_list = M("comment")
                        ->alias("c")
                        ->join("f_users u","c.user_id = u.user_id","left")
                        ->where(array("c.goods_id" =>$goods_id,"c.is_show"=>1))
                        ->order("c.add_time desc")
                        ->field("c.*,u.head_pic")
                        ->limit($page*$limit,$limit)
                        ->select();
        foreach ($comment_list as $key => $value){
            $comment_list[$key]['img'] = unserialize($value['img']);
            $comment_list[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']); 
        } 
        if(IS_AJAX){
            if(count($comment_list) > 0){
                $back['status'] = 1;
                $back['msg'] = "查询成功";
                $back['data'] = $comment_list;
            }else{
                $back['status'] = 0;
                $back['msg'] = "查询失败";
                $back['data'] = "无数据";
            }
            echo json_encode($back);
            exit();
        }
        $comment_count = M("comment")->where(array("goods_id" =>$goods_id,"is_show"=>1))->count();
        $pagecount = ceil($comment_count/$limit);
        $this->assign("goods_id",$goods_id);
        $this->assign("pagecount",$pagecount);
        $this->assign("comment_list",$comment_list);
        return $this->fetch();
    }
    
}